package com.dayuanit.atm.service;

import com.dayuanit.atm.dto.FlowDTO;
import com.dayuanit.atm.handler.MessageHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class RedisService {

    @Autowired
    private RedisTemplate<String, List<FlowDTO>> top10FlowsTemp;

    @Autowired
    private RedisTemplate redisTemplate;

//    @Autowired
//    private RedisTemplate<String, MessageHolder> queueMessageTemp;

    @Resource(name = "redisTemplate")
    private ListOperations<String, MessageHolder> queueMessageTemp;

    @Resource(name = "redisTemplate")
    private HashOperations hashTemp;

    public void saveTop10Flow(int userId, List<FlowDTO> flowDTOS) {
        String key = "top10:" + userId;
        top10FlowsTemp.opsForValue().set(key, flowDTOS);
    }

    public List<FlowDTO> getTop10Flows(int userId) {
        String key = "top10:" + userId;
        return top10FlowsTemp.opsForValue().get(key);

    }

    public void setExpirtTime(int key, int timeout) {
        redisTemplate.expire(key, timeout, TimeUnit.SECONDS);
    }

    public void pushMessage(int userId, String message) {
        MessageHolder messageHolder = new MessageHolder();
        messageHolder.setMessage(message);
        messageHolder.setUserId(userId);

        String key = "transfer:message";
//        queueMessageTemp.opsForList().leftPush(key, messageHolder);
        queueMessageTemp.leftPush(key, messageHolder);
    }

    public MessageHolder popMessage() {
        String key = "transfer:message";
//        return queueMessageTemp.opsForList().rightPop(key, 2000, TimeUnit.SECONDS);
        return queueMessageTemp.rightPop(key, 2000, TimeUnit.SECONDS);
    }
}
